<template>
  <div class="app-container">
    <!-- 筛选 -->
    <el-card>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form :inline="true" :model="queryParams" class="filter-form">
          <el-form-item label="时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>

          <el-form-item label="库位号">
            <el-input
              v-model="queryParams.locationNo"
              placeholder="请输入库位号"
              clearable
              @keydown.enter.prevent="handleQuery"
            />
          </el-form-item>

          <el-form-item label="料号">
            <el-input
              v-model="queryParams.materialNo"
              placeholder="请输入料号"
              clearable
              @keydown.enter.prevent="handleQuery"
            />
          </el-form-item>

          <el-form-item label="报关单号">
            <el-input
              v-model="queryParams.customsNo"
              placeholder="请输入报关单号"
              clearable
              @keydown.enter.prevent="handleQuery"
            />
          </el-form-item>

          <el-form-item label="品名">
            <el-input
              v-model="queryParams.productName"
              placeholder="请输入品名"
              clearable
              @keydown.enter.prevent="handleQuery"
            />
          </el-form-item>
          <el-form-item label="许可证号">
            <el-select
              v-model="queryParams.licenseNo"
              placeholder="请选择许可证号"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="item in licenseOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="mt20">
      <el-row justify="space-between" class="mb10">
        <span style="font-size: 18px">成品记录</span>
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新增记录</el-button
        >
      </el-row>

      <el-table :data="recordList" border stripe v-loading="loading">
        <el-table-column prop="operateDate" label="日期" />
        <el-table-column prop="contractNo" label="料号" />
        <el-table-column prop="productName" label="品名" />
        <el-table-column prop="by14" label="库位" />
        <el-table-column prop="customsNo" label="报关单号" />
        <el-table-column prop="transferNo" label="调运单号" />
        <el-table-column prop="licenseNo" label="许可证号" />
        <el-table-column prop="orderNo" label="工单号" />
        <el-table-column prop="totalWeight" label="入库总重量(吨)" />
        <el-table-column prop="packageCount" label="打包数量" />
        <el-table-column label="计数器照片">
          <template #default="{ row }">
            <el-button
              v-if="row.counterPic"
              type="primary"
              link
              @click="previewImage(row.counterPic)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="singlePackageWeight" label="单包重量(kg)" />
        <el-table-column prop="recordDate" label="记账日期" />
        <el-table-column prop="licenseDate" label="凭证日期" />
        <el-table-column label="流量称照片">
          <template #default="{ row }">
            <el-button
              v-if="row.documentImage"
              type="primary"
              link
              @click="previewImage(row.documentImage)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="入库单">
          <template #default="{ row }">
            <el-button
              v-if="row.inboundPic"
              type="primary"
              link
              @click="previewImage(row.inboundPic)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="curChargePerson" label="负责人" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewDetail(row)"
              >编辑</el-button
            >
            <el-button
              v-hasPermi="['packing:all:delete']"
              link
              type="danger"
              @click="deleteRow(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '编辑记录' : '新增记录'"
      width="600px"
    >
      <el-form :model="formData" label-width="120px">
        <el-form-item label="时间">
          <el-date-picker
            v-model="formData.operateDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="料号">
          <el-select
            v-model="formData.contractNo"
            placeholder="请选择料号"
            style="width: 100%"
          >
            <el-option
              v-for="item in liaohaoOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品名">
          <el-input v-model="formData.productName" />
        </el-form-item>
        <el-form-item label="库位号">
          <el-select
            v-model="formData.by14"
            placeholder="请选择库位号"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in kuweiOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报关单号">
          <el-select
            v-model="formData.customsNo"
            placeholder="请选择报关单号"
            filterable
            clearable
          >
            <el-option
              v-for="item in customsOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调运单号">
          <el-input v-model="formData.transferNo" />
        </el-form-item>
        <el-form-item label="许可证号">
          <el-select
            v-model="formData.licenseNo"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in licenseOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单号">
          <el-input v-model="formData.orderNo" />
        </el-form-item>
        <el-form-item label="入库总重量(吨)">
          <el-input v-model="formData.totalWeight" disabled />
        </el-form-item>
        <el-form-item label="打包数量">
          <el-input-number
            v-model="formData.packageCount"
            :min="0"
            @change="calcTotalWeight"
          />
        </el-form-item>
        <el-form-item label="计数器照片">
          <el-upload
            class="upload-demo"
            action="/dev-api/minio/upload"
            :on-success="handleUploadSuccess1"
            :on-remove="handleRemove1"
            :file-list="formData.documentImageList1"
            :limit="1"
            list-type="picture-card"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="流量称照片">
          <el-upload
            class="upload-demo"
            action="/dev-api/minio/upload"
            :on-success="handleUploadSuccess2"
            :on-remove="handleRemove2"
            :file-list="formData.documentImageList2"
            :limit="1"
            list-type="picture-card"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="入库单">
          <el-upload
            class="upload-demo"
            action="/dev-api/minio/upload"
            :on-success="handleUploadSuccess3"
            :on-remove="handleRemove3"
            :file-list="formData.documentImageList3"
            :limit="1"
            list-type="picture-card"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="单包重量(kg)">
          <el-input-number
            v-model="formData.singlePackageWeight"
            :min="0"
            @change="calcTotalWeight"
          />
        </el-form-item>
        <el-form-item label="记账日期">
          <el-date-picker
            v-model="formData.recordDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="凭证日期">
          <el-date-picker
            v-model="formData.licenseDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="formData.curChargePerson" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="[imagePreviewUrl]"
      @close="showImageViewer = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  packing_add as addOrder,
  packing_delete as delOrder,
  packing_edit as updateOrder,
  packing_list as listOrder,
} from "@/api/wms/packing";
import {
  queryLicenseList,
  queryCustomsNoList,
  queryMaterialNoList,
  queryStorageNoList,
} from "@/api/wms/whole";
import { ElImageViewer } from "element-plus";
import { getToken } from "@/utils/auth";

// 状态
const loading = ref(false);
const total = ref(0);
const daipi = ref(0);
const dialogVisible = ref(false);
const licenseOptions = ref([]);
// 日期范围
const dateRange = ref([]); // [start, end]
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  licenseNo: "",
  materialNo: "",
  customsNo: "",
  productName: "",
  operateStartDate: "",
  operateEndDate: "",
});

const recordList = ref([]);
const formData = reactive({
  id: null,
  operateDate: "",
  contractNo: "",
  productName: "",
  by14: "",
  customsNo: "",
  transferNo: "",
  licenseNo: "",
  orderNo: "",
  totalWeight: "",
  packageCount: "",
  counterPic: "",
  singlePackageWeight: "",
  recordDate: "",
  licenseDate: "",
  documentImage: "",
  inboundPic: "",
  curChargePerson: "",
  documentImageList1: [],
  documentImageList2: [],
  documentImageList3: [],
});
const headers = ref({ Authorization: "Bearer " + getToken() });
const showImageViewer = ref(false);
const imagePreviewUrl = ref("");
const customsOptions = ref([]);
const liaohaoOptions = ref([]);
const kuweiOptions = ref([]);

function previewImage(url) {
  imagePreviewUrl.value = url;
  showImageViewer.value = true;
}
// 查询列表
async function handleQuery() {
  if (dateRange.value && dateRange.value.length) {
    queryParams.operateStartDate = dateRange.value[0];
    queryParams.operateEndDate = dateRange.value[1];
  } else {
    queryParams.operateStartDate = "";
    queryParams.operateEndDate = "";
  }
  loading.value = true;
  try {
    const res = await listOrder(queryParams);
    recordList.value = res.rows || [];
    total.value = res.total || 0;
  } catch {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
}

async function loadSelectOptions() {
  try {
    const [customsRes, liaohao, kuwei] = await Promise.all([
      queryCustomsNoList(),
      queryMaterialNoList(),
      queryStorageNoList(),
    ]);
    customsOptions.value = customsRes.data.filter((pre) => pre) || [];
    liaohaoOptions.value = liaohao.data.filter((pre) => pre) || [];
    kuweiOptions.value = ["成品库"];
  } catch (e) {
    ElMessage.error("加载下拉选项失败");
  }
}

// 重置
function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    licenseNo: "",
    materialNo: "",
    productName: "",
    customsNo: "",
    operateStartDate: "",
    operateEndDate: "",
  });
  dateRange.value = [];
  handleQuery();
}

// 新增
function handleAdd() {
  Object.assign(formData, {
    id: "",
    operateDate: "",
    contractNo: "",
    productName: "",
    by14: "",
    customsNo: "",
    transferNo: "",
    licenseNo: "",
    orderNo: "",
    totalWeight: "",
    packageCount: "",
    counterPic: "",
    singlePackageWeight: "",
    recordDate: "",
    licenseDate: "",
    documentImage: "",
    inboundPic: "",
    curChargePerson: "",
    documentImageList1: [],
    documentImageList2: [],
    documentImageList3: [],
  });
  dialogVisible.value = true;
}

// 编辑
function viewDetail(row) {
  Object.assign(formData, {
    ...row,
    documentImageList: row.documentImage
      ? [
          {
            name: "预览图",
            url: row.documentImage,
          },
        ]
      : [],
  });
  dialogVisible.value = true;
}

// 删除
function deleteRow(row) {
  ElMessageBox.confirm("是否删除此项?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await delOrder(row.id);
      ElMessage.success("删除成功");
      handleQuery();
    } catch {
      ElMessage.error("删除失败");
    }
  });
}

// 计算总重量
function calcTotalWeight() {
  formData.totalWeight = (
    (Number(formData.packageCount) * Number(formData.singlePackageWeight)) /
    1000
  ).toFixed(4);
  daipi.value = ((Number(formData.packageCount) * 0.06) / 1000).toFixed(4);
}

// 提交
async function submitForm() {
  formData.operateDate = dayjs(formData.operateDate).format("YYYY-MM-DD");
  calcTotalWeight();
  formData.recordDate = dayjs(formData.recordDate).format("YYYY-MM-DD");
  calcTotalWeight();
  formData.licenseDate = dayjs(formData.licenseDate).format("YYYY-MM-DD");
  calcTotalWeight();
  formData.documentImage =
    formData.documentImageList2.length > 0
      ? formData.documentImageList2[0].url
      : "";
  formData.counterPic =
    formData.documentImageList1.length > 0
      ? formData.documentImageList1[0].url
      : "";
  formData.inboundPic =
    formData.documentImageList3.length > 0
      ? formData.documentImageList3[0].url
      : "";

  try {
    if (formData.id) {
      await updateOrder(formData);
      ElMessage.success("更新成功");
    } else {
      await addOrder(formData);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    handleQuery();
  } catch {
    ElMessage.error("提交失败");
  }
}

// 文件上传成功1
function handleUploadSuccess1(res, file, fileList) {
  formData.documentImageList1 = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
}

// 删除上传1
function handleRemove1(file, fileList) {
  formData.documentImageList1 = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
}
// 文件上传成功2
function handleUploadSuccess2(res, file, fileList) {
  formData.documentImageList2 = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
}

// 删除上传2
function handleRemove2(file, fileList) {
  formData.documentImageList2 = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
}

// 文件上传成功3
function handleUploadSuccess3(res, file, fileList) {
  formData.documentImageList3 = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
}

// 删除上传3
function handleRemove3(file, fileList) {
  formData.documentImageList3 = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
}

// 获取物料凭证号列表
async function loadLicenseOptions() {
  const res = await queryLicenseList();
  licenseOptions.value = (res.data || []).map((item) => {
    // 如果是字符串，按 . 分割；如果是数字，先转成字符串
    return String(item).split(".")[0];
  });
}

// 初始化
onMounted(() => {
  handleQuery();
  loadLicenseOptions();
  loadSelectOptions();
});
</script>

<style scoped>
.mt20 {
  margin-top: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
